package com.flycms.module.soft.service;

import com.flycms.core.entity.PageVo;
import com.flycms.module.soft.dao.SoftDao;
import com.flycms.module.soft.dao.SoftSceneDao;
import com.flycms.module.soft.model.Soft;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.flycms.module.soft.model.SoftDetial;
import com.flycms.module.soft.model.SoftScene;
import com.flycms.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author huangzt
 * @version 1.0
 * @date 2020/3/7 17:07
 */
@Service
public class SoftService {
    @Autowired
    SoftDao softDao;
    @Autowired
    SoftSceneDao sceneDao;

    public int insert(Soft soft) {
        return softDao.insert(soft);
    }

    public int update(Soft soft) {
        return softDao.update(soft);
    }

    public Soft queryByPk(Integer id, Integer status) {
        return softDao.queryByPk(id, status);
    }

    public int delete(Integer id) {
        return softDao.delete(id);
    }

    public PageVo<Soft> queryByPage(String softName, Integer categoryId, String softPlatform, Integer status,
            String orderby, String order, Integer pageIndex, Integer pageSzie) {
        if (orderby == null) {
            orderby = "update_time";
        }
        if (order == null) {
            order = "desc";
        }
        PageVo<Soft> pageVo = new PageVo<>(pageIndex);
        pageVo.setRows(pageSzie);
        pageVo.setList(softDao.queryByPage(softName, categoryId, softPlatform, status, orderby, order,
                pageVo.getOffset(), pageVo.getRows()));
        pageVo.setCount(softDao.countSoft(softName, categoryId, softPlatform, status));
        return pageVo;
    }

    public List<Soft> queryByIds(List<Integer> ids) {
        return softDao.queryByIds(ids);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void insertSoftDetail(SoftDetial soft) throws Exception{
        soft.setCreate_time(new Date());
        soft.setUpdate_time(new Date());
        soft.setStatus(1);
        Soft soft1 = ConvertUtils.sourceToTarget(soft,Soft.class);
        softDao.insert(soft1);
        List<SoftScene> sceneList = soft.getSceneList();
        List<SoftScene> list = sceneList.stream().map(a->{
            a.setSoft_id(soft1.getId());
            a.setCreate_time(new Date());
            a.setUpdate_time(new Date());
            return a;
        }).collect(Collectors.toList());
        sceneDao.insertForEach(list);
    }
}
